package weaver.interfaces.login.filter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HtscLoginFilter implements Filter{
    protected final Log log = LogFactory.getLog(getClass());

    private ServletContext application;

    private String excludedPages;
    private String excludedPaths;
    private String[] excludedPageArray;
    private String[] excludedPathArray;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.application = filterConfig.getServletContext();
        this.excludedPages = filterConfig.getInitParameter("excludedPages");
        BaseBean bb = new BaseBean();
        bb.writeLog("excludedPages:"+this.excludedPages);
        this.excludedPaths = filterConfig.getInitParameter("excludedPaths");
        bb.writeLog("excludedPages:"+this.excludedPages);

        if(StringUtils.isNotEmpty(this.excludedPages))
        {
            this.excludedPageArray = this.excludedPages.split(";");
        }

        if(StringUtils.isNotEmpty(this.excludedPaths))
        {
            this.excludedPathArray = this.excludedPaths.split(";");
        }
    }

    public void doFilter(ServletRequest ServletRequest, ServletResponse ServletResponse,FilterChain FilterChain) throws ServletException, IOException
    {
        BaseBean bb = new BaseBean();
        HttpServletRequest request = (HttpServletRequest)ServletRequest;
        HttpServletResponse response = (HttpServletResponse)ServletResponse;

//        bb.writeLog("getPathInfo():"+request.getPathInfo());
        bb.writeLog("getRequestURI:"+request.getRequestURI());
//        bb.writeLog("getServletPath:"+request.getServletPath());

        String getRequestURI = request.getRequestURI();
        boolean isExcludedPage = false;
        for (String page : excludedPageArray) { //判断是否在过滤url之外
            if(getRequestURI.equals(page))
            {
                isExcludedPage = true;
                break;
            }
        }

        if(!isExcludedPage){
            for (String path : excludedPathArray) { //判断是否在过滤url之外
                if(getRequestURI.contains(path))
                {
                    isExcludedPage = true;
                    break;
                }

            }
        }
        if(!isExcludedPage){
            String uncheckurl = bb.getPropValue("weaver_session_filter.prpperties","uncheckurl");
            if(uncheckurl.contains(getRequestURI)){
                isExcludedPage = true;

            }
            String unchecksessionurl = bb.getPropValue("weaver_session_filter.prpperties","unchecksessionurl");
            if(unchecksessionurl.contains( getRequestURI)){
                isExcludedPage = true;
            }

        }
//        bb.writeLog("isExcludedPage:"+isExcludedPage);
        if (isExcludedPage) { //在过滤url之外
            bb.writeLog("111111");
            FilterChain.doFilter(request, response);
        } else { //不在过滤url之外，判断登录

            bb.writeLog("111111");

            RecordSet rs = new RecordSet();
//            bb.writeLog("HtscLoginFilter6666666666666666");
            if (StringUtils.isNotBlank(request.getHeader("x-requested-with"))) {
                request.setCharacterEncoding("UTF-8");
            }
//            String htuserid = "";
//            Enumeration<String> reqHeadInfos = request.getHeaderNames();//获取所有的请求头
//            while (reqHeadInfos.hasMoreElements()) {
//                String headName = (String) reqHeadInfos.nextElement();
//                if ("iv-user".equalsIgnoreCase(headName)) {
//                    htuserid = request.getHeader(headName);
//                }
//            }

            String htuserid = Util.null2String(request.getHeader("iv_user"));
            User user = (User) request.getSession(true).getAttribute("weaver_user@bean");
            if (user == null)
            {
                if(!"".equals(htuserid))
                {
                    User user_new = null;
                    String sql = " select * from hrmresource where loginid='" + htuserid + "'";
                    rs.execute(sql);
                    if (rs.next())
                    {
                        user_new = new User();
                        user_new.setUid(rs.getInt("id"));
                        user_new.setLoginid(rs.getString("loginid"));
                        user_new.setFirstname(rs.getString("firstname"));
                        user_new.setLastname(rs.getString("lastname"));
                        user_new.setAliasname(rs.getString("aliasname"));
                        user_new.setTitle(rs.getString("title"));
                        user_new.setTitlelocation(rs.getString("titlelocation"));
                        user_new.setSex(rs.getString("sex"));
                        user_new.setPwd(rs.getString("password"));
                        String languageidweaver = rs.getString("systemlanguage");
                        user_new.setLanguage(Util.getIntValue(languageidweaver, 0));

                        user_new.setTelephone(rs.getString("telephone"));
                        user_new.setMobile(rs.getString("mobile"));
                        user_new.setMobilecall(rs.getString("mobilecall"));
                        user_new.setEmail(rs.getString("email"));
                        user_new.setCountryid(rs.getString("countryid"));
                        user_new.setLocationid(rs.getString("locationid"));
                        user_new.setResourcetype(rs.getString("resourcetype"));
                        user_new.setStartdate(rs.getString("startdate"));
                        user_new.setEnddate(rs.getString("enddate"));
                        user_new.setContractdate(rs.getString("contractdate"));
                        user_new.setJobtitle(rs.getString("jobtitle"));
                        user_new.setJobgroup(rs.getString("jobgroup"));
                        user_new.setJobactivity(rs.getString("jobactivity"));
                        user_new.setJoblevel(rs.getString("joblevel"));
                        user_new.setSeclevel(rs.getString("seclevel"));
                        user_new.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
                        user_new.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
                        user_new.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
                        user_new.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
                        user_new.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
                        user_new.setManagerid(rs.getString("managerid"));
                        user_new.setAssistantid(rs.getString("assistantid"));
                        user_new.setPurchaselimit(rs.getString("purchaselimit"));
                        user_new.setCurrencyid(rs.getString("currencyid"));
                        user_new.setLastlogindate(rs.getString("currentdate"));
                        user_new.setLogintype("1");
                        user_new.setAccount(rs.getString("account"));
                        user_new.setLoginip(request.getRemoteAddr());

                        //System.out.println(">>>>>>>>>>>>>>begin>>>>>>>>>>>>>>"+request.getSession(true).getId());
                        String weaver_login_type = Util.null2String(request.getSession(true).getAttribute("weaver_login_type"));
                        request.getSession(true).invalidate();
                        //System.out.println(">>>>>>>>>>>>>>after>>>>>>>>>>>>>>"+request.getSession(true).getId());
                        request.getSession(true).setAttribute("weaver_login_type", weaver_login_type);
                        request.getSession(true).setAttribute("weaver_user@bean", user_new);
                        request.getSession(true).setAttribute("rtxlogin", "1");

                        Util.setCookie(response, "loginidweaver", user_new.getUID() + "", -1);
                        Util.setCookie(response, "languageidweaver", Util.null2s(languageidweaver, "7"), -1);
                    }
                }else{
                    response.sendRedirect("http://eipsit.htsc.com.cn/htoa");
                }
            }
            bb.writeLog(request.getSession(true).getId());
            User userlogin = (User)request.getSession(true).getAttribute("weaver_user@bean") ;
            if(userlogin !=null)
            {
                //bb.writeLog("userlogin:"+userlogin.getLoginid());
                if("/htoa/".equals(getRequestURI) || "/htoa".equals(getRequestURI) ||  "/htoa/wui/index.html".equals(getRequestURI)){
                    response.sendRedirect("/htoa/wui/index.html?#/main");
                }
            }
            FilterChain.doFilter(request, response);
        }

//        else{
//            String loginid = user.getLoginid();
//            if(!htuserid.equals(loginid))
//            {
//                bb.writeLog("2222222:");
//                User user_new = null;
//                String sql = " select * from hrmresource where loginid='"+htuserid+"'" ;
//                rs.execute(sql);
//                if(rs.next())
//                {
//                    user_new = new User();
//                    user_new.setUid(rs.getInt("id"));
//                    user_new.setLoginid(rs.getString("loginid"));
//                    user_new.setFirstname(rs.getString("firstname"));
//                    user_new.setLastname(rs.getString("lastname"));
//                    user_new.setAliasname(rs.getString("aliasname"));
//                    user_new.setTitle(rs.getString("title"));
//                    user_new.setTitlelocation(rs.getString("titlelocation"));
//                    user_new.setSex(rs.getString("sex"));
//                    user_new.setPwd(rs.getString("password"));
//                    String languageidweaver = rs.getString("systemlanguage");
//                    user_new.setLanguage(Util.getIntValue(languageidweaver, 0));
//
//                    user_new.setTelephone(rs.getString("telephone"));
//                    user_new.setMobile(rs.getString("mobile"));
//                    user_new.setMobilecall(rs.getString("mobilecall"));
//                    user_new.setEmail(rs.getString("email"));
//                    user_new.setCountryid(rs.getString("countryid"));
//                    user_new.setLocationid(rs.getString("locationid"));
//                    user_new.setResourcetype(rs.getString("resourcetype"));
//                    user_new.setStartdate(rs.getString("startdate"));
//                    user_new.setEnddate(rs.getString("enddate"));
//                    user_new.setContractdate(rs.getString("contractdate"));
//                    user_new.setJobtitle(rs.getString("jobtitle"));
//                    user_new.setJobgroup(rs.getString("jobgroup"));
//                    user_new.setJobactivity(rs.getString("jobactivity"));
//                    user_new.setJoblevel(rs.getString("joblevel"));
//                    user_new.setSeclevel(rs.getString("seclevel"));
//                    user_new.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
//                    user_new.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
//                    user_new.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
//                    user_new.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
//                    user_new.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
//                    user_new.setManagerid(rs.getString("managerid"));
//                    user_new.setAssistantid(rs.getString("assistantid"));
//                    user_new.setPurchaselimit(rs.getString("purchaselimit"));
//                    user_new.setCurrencyid(rs.getString("currencyid"));
//                    user_new.setLastlogindate(rs.getString("currentdate"));
//                    user_new.setLogintype("1");
//                    user_new.setAccount(rs.getString("account"));
//                    user_new.setLoginip(request.getRemoteAddr());
//
//                    //System.out.println(">>>>>>>>>>>>>>begin>>>>>>>>>>>>>>"+request.getSession(true).getId());
//                    String weaver_login_type = Util.null2String(request.getSession(true).getAttribute("weaver_login_type"));
//                    request.getSession(true).invalidate();
//                    //System.out.println(">>>>>>>>>>>>>>after>>>>>>>>>>>>>>"+request.getSession(true).getId());
//                    request.getSession(true).setAttribute("weaver_login_type",weaver_login_type);
//                    request.getSession(true).setAttribute("weaver_user@bean", user_new);
//                    request.getSession(true).setAttribute("rtxlogin", "1");
//
//                    Util.setCookie(response, "loginidweaver", user_new.getUID() + "", -1);
//                    Util.setCookie(response, "languageidweaver", Util.null2s(languageidweaver, "7"), -1);
//                }
//            }else{
//                bb.writeLog("33333:");
//            }
//        }

    }
    public void destroy() {

    }

}
